import loadEnvConfig from '@src/util/loadEnv';
import { drizzle } from 'drizzle-orm/mysql2';
import mysql2 from 'mysql2/promise';

// 初始化环境变量
loadEnvConfig();

// 验证必需的环境变量
if (!process.env.DATABASE_URL) {
  throw new Error('DATABASE_URL environment variable is required');
}

// 为 express-mysql-session 创建普通的 mysql2 连接池
const pool = mysql2.createPool(process.env.DATABASE_URL);

// 选项 casing: 'snake_case' 可以映射驼峰到 snaking 命名，在代码中使用驼峰，数据库中使用 snaking
// 为 drizzle 创建数据库实例
const db = drizzle(pool);

/**
 * 测试数据库连接
 */
export async function testConnection(): Promise<void> {
  try {
    const connection = await pool.getConnection();
    console.log('✅ Database connection successful');
    connection.release();
  } catch (error) {
    console.error('❌ Database connection failed:', error);
    throw error;
  }
}

/**
 * 优雅关闭数据库连接池
 */
export async function closePool(): Promise<void> {
  try {
    await pool.end();
    console.log('✅ Database pool closed');
  } catch (error) {
    console.error('❌ Error closing database pool:', error);
    throw error;
  }
}

// 导出连接池和数据库实例
export { pool, db };
